package ru.ifmo.thesis.solver.gp;

import org.jgap.Genotype;
import org.jgap.IChromosome;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.ifmo.thesis.domain.Shedule;
import ru.ifmo.thesis.util.Algorithms;

public class NoChangesRule implements CompletionRule {

	private static final Logger logger = LoggerFactory.getLogger(NoChangesRule.class);
	
	private final int maxStagnation;
	
	private int currentStagnation = 0;
	
	private double lastSheduleCost = -1.0d;
	
	public NoChangesRule(int maxStagnation) {
		this.maxStagnation = maxStagnation;
	}
	
	@Override
	public boolean isTaskCompleted(Genotype population) {
		IChromosome fittestChromosome = population.getFittestChromosome();
		Shedule shedule = Algorithms.constructShedule(fittestChromosome);
		double currentSheduleCost = Algorithms.calculateSheduleCost(shedule);
		if (currentSheduleCost != lastSheduleCost) {
			currentStagnation = 0;
		} else {
			currentStagnation++;
		}

		logger.debug(String.format("###### shedule=%d, last=%f, current=%f, stagnation=%d", 
				shedule.hashCode(), lastSheduleCost, currentSheduleCost, currentStagnation));
	
		lastSheduleCost = currentSheduleCost;

		return currentStagnation >= maxStagnation;
	}

	@Override
	public CompletionRule newCopy() {
		return new NoChangesRule(maxStagnation);
	}

}
